C/C++时区正确的时间转换(自纪元以来的秒数) 您所在的位置:网站首页 unity gf框架 C/C++时区正确的时间转换(自纪元以来的秒数)

C/C++时区正确的时间转换(自纪元以来的秒数)

2023-04-06 06:54| 来源: 网络整理| 查看: 265

; std::chrono::minutes parse_offset(std::istream& in) { using namespace std::chrono; char c; in >> c; minutes result = 10*hours{c - '0'}; in >> c; result += hours{c - '0'}; in >> c; result += 10*minutes{c - '0'}; in >> c; result += minutes{c - '0'}; return result; } second_point parse(const std::string& str) { std::istringstream in(str); in.exceptions(std::ios::failbit | std::ios::badbit); int yi, mi, di; char dash; // check dash if you're picky in >> yi >> dash >> mi >> dash >> di; using namespace date; auto ymd = year{yi}/mi/di; // check ymd.ok() if you're picky char T; in >> T; // check T if you're picky int hi, si; char colon; in >> hi >> colon >> mi >> colon >> si; // check colon if you're picky using namespace std::chrono; auto h = hours{hi}; auto m = minutes{mi}; auto s = seconds{si}; second_point result = sys_days{ymd} + h + m + s; char f; in >> f; if (f == '+') result -= parse_offset(in); else if (f == '-') result += parse_offset(in); else ;// check f == 'Z' if you're picky return result; } int main() { using namespace date; std::cout

要完全前期,该解决方案使主要用途的std::istringstream,std::chrono以及实际上只是它的非常小的一部分是我最新的图书馆.

我做了几个设计选择,您可以选择不选择(解析时有很多选项).例如,如果存在任何解析错误,我选择抛出异常,并且我选择不挑选检查分隔符等(-并且:主要是出于简洁的原因).

代码相对不言自明.正如您在问题中所述,本地时区不是(也不应该是)解决方案的一部分.计时库用于在小时,分钟和秒之间管理算术.我的日期库用于处理年/月/日转换chrono::time_point为精度为days.

处理完所有这些算术后,您可以专注于解析整数和字符.可以直接向此示例添加更多检查,并为错误执行任何操作.

此示例输出:

1440671500s 1440671500s

更新

我已经添加了解析功能,现在可以更简单地编写"date.h"上面的parse函数:

date::sys_seconds parse(const std::string& str) { std::istringstream in(str); date::sys_seconds tp; in >> date::parse("%FT%TZ", tp); if (in.fail()) { in.clear(); in.str(str); in >> date::parse("%FT%T%z", tp); } return tp; } int main() { using namespace date; std::cout

并返回相同的结果.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有